/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.core.provider.transport;

import com.alibaba.fastjson.JSON;
import com.lvyh.lightframe.core.filter.FilterChain;
import com.lvyh.lightframe.core.filter.ProviderFilterChain;
import com.lvyh.lightframe.core.invoke.request.Heartbeat;
import com.lvyh.lightframe.core.invoke.request.RpcRequest;
import com.lvyh.lightframe.core.invoke.response.RpcResponse;
import com.lvyh.lightframe.core.util.SpringContextUtils;
import com.lvyh.lightframe.common.util.ThreadPoolUtils;
import com.lvyh.lightframe.common.util.ThrowableUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ThreadPoolExecutor;


public class NettyServerHandler extends SimpleChannelInboundHandler<RpcRequest> {
    private static final Logger logger = LoggerFactory.getLogger(NettyServerHandler.class);

    private ThreadPoolExecutor threadPoolExecutor = ThreadPoolUtils.makeServerThreadPool(NettyServerBootstrap.class.getSimpleName(), 60, 300);

    public NettyServerHandler() {
    }


    @Override
    public void channelRead0(final ChannelHandlerContext ctx, final RpcRequest rpcRequest) throws Exception {

        if (Heartbeat.PING_REQ_ID.equalsIgnoreCase(rpcRequest.getRequestId())) {
            logger.info("[NettyServerHandler] server receive heart beat req.");
            return;
        }

        logger.info("[NettyServerHandler] server receive request, param:{}", JSON.toJSONString(rpcRequest));
        try {
            threadPoolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    FilterChain filterChain = SpringContextUtils.getBean(ProviderFilterChain.class);
                    RpcResponse rpcResponse = filterChain.filter(rpcRequest);
                    ctx.writeAndFlush(rpcResponse);
                }
            });
        } catch (Exception e) {
            RpcResponse rpcResponse = new RpcResponse();
            rpcResponse.setRequestId(rpcRequest.getRequestId());
            rpcResponse.setErrorMsg(ThrowableUtil.toString(e));
            ctx.writeAndFlush(rpcResponse);
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable t) {
        logger.error("[NettyServerHandler] server error,", t);
        ctx.close();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            ctx.channel().close();
            logger.info("[NettyServerHandler] server close an idle channel.");
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

}
